﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web.UI;
using System.Reflection;
using System.Text.RegularExpressions;

namespace EZCRS.HCMS.Bll.AIR
{

    public class TemplateRender<T>
    {
        private T _obj;

        private Dictionary<string, object> _dicKeyValues;

        public TemplateRender(T obj)
        {
            _obj = obj;

            Type t = _obj.GetType();

            __FillValues(t);
        }

        protected string _strTemplate;

        public string Template
        {
            set
            {
                _strTemplate = value;
            }
            get
            {
                return _strTemplate;
            }
        }

        static string CustomReplace(System.Text.RegularExpressions.Match m)
        {
            return m.Groups[1].Value;
        }

        public virtual string Render()
        {
            
            MatchEvaluator mymatch = new MatchEvaluator(CustomReplace);

            foreach (string key in _dicKeyValues.Keys)
            {
                string pattern = @"<%\s" + key + @"\s+%>";

                Regex reg = new Regex(pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase |
    System.Text.RegularExpressions.RegexOptions.Multiline);

                _strTemplate = reg.Replace(_strTemplate, _dicKeyValues[key].ToString());
            }

            return _strTemplate;

        }

        private void __FillValues(Type type)
        {
            if (_dicKeyValues == null)
            {
                _dicKeyValues = new Dictionary<string, object>();

                foreach (PropertyInfo pi in type.GetProperties())
                {
                    object obj = pi.GetValue(_obj, null);

                    if (obj != null)
                        _dicKeyValues.Add(pi.Name, obj);

                }
            }
        }
    }

}
